package edu.hcmus.sow.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import edu.hcmus.sow.dao.RepositoryDAO;
import edu.hcmus.sow.domain.repository.FileInfo;
import edu.hcmus.sow.web.security.CustomWebAuthenticationDetails;

@Service
public class RepositoryService {

   @Autowired
   private RepositoryDAO repositoryDAO;

   public FileInfo saveFile(InputStream stream) throws IOException {
      String key = UUID.randomUUID().toString();
      long size = repositoryDAO.saveFile(getStorageName(), key, stream);

      FileInfo fi = new FileInfo(key, size);
      return fi;
   }

   public void readFile(String key, OutputStream stream) throws IOException {
      repositoryDAO.readFile(getStorageName(), key, stream);
   }

   public void deleteFile(String key) {
      repositoryDAO.deleteFile(getStorageName(), key);
   }

   public void createFileStorage(String name) {
      repositoryDAO.createFileStorage(name);
   }

   public void dropFileStorage(String name) {
      repositoryDAO.dropFileStorage(name);
   }

   private String getStorageName() {
      Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
      String subdomain = ((CustomWebAuthenticationDetails) authentication.getDetails()).getSubDomain();
      return StringUtils.isEmpty(subdomain) ? "sow" : subdomain;
   }
}